package com.jinjie.exception;


import com.jinjie.base.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class GlobalExceptionController implements ErrorController {
    private static final String ERROR_PATH = "/error";


    @RequestMapping(value = ERROR_PATH)
    public Result error(HttpServletRequest request) {
        WebRequest webRequest = new ServletWebRequest(request);
        Throwable e = getError(webRequest);
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if(!ObjectUtils.isEmpty(status)){
            int statusCode = Integer.parseInt(status.toString());
            if (statusCode == HttpStatus.NOT_FOUND.value()) {
                // 处理 404 错误
//                return "404"; // 返回自定义的 404 页面的视图名称，需要在模板引擎中创建对应的 404.html 页面
                return Result.error(Integer.parseInt(status.toString()), "访问地址有误，请确认请求！");
            }
        }
        if (e == null) {

            Object timestamp = webRequest.getAttribute("timestamp",404);
            status =webRequest.getAttribute("status",404);
            String error = webRequest.getAttribute("error",404).toString();
            Object path = webRequest.getAttribute("path",404);
            log.error("status {} error {} path{} timestamp {}", status, error, path, timestamp);
            return Result.error(Integer.parseInt(status.toString()), error);
        }
        if (e instanceof Exception) {
            Exception codeException = (Exception) e;
            String message = e.getMessage();
            if (StringUtils.isEmpty(message)) {
                message = String.format("[%s]",  codeException.getMessage());
            }
            return  Result.error(message);
        } else {
            return  Result.error("系统繁忙,请稍后再试");
        }
    }

    private Throwable getError(WebRequest webRequest) {
        return (Throwable) this.getAttribute(webRequest, "javax.servlet.error.exception");
    }

    private Object getAttribute(RequestAttributes requestAttributes, String name) {
        return requestAttributes.getAttribute(name, 0);
    }

}
